package m.store.service;

import m.base.util.PowerUtil;
import m.common.model.util.ModelQueryList;
import m.common.model.util.ModelUpdateUtil;
import m.common.model.util.QueryCondition;
import m.common.service.Service;
import m.store.model.*;
import m.store.task.StoreGoodsSupport;
import m.system.db.TransactionManager;
import m.system.exception.MException;

import java.util.*;
import java.util.stream.Collectors;

public class GoodsOutVirtualStockService extends Service {
    /**
     * 生产调拨入库
     */
    public void convertGoodsStockRecord(String saleOid) throws Exception {
        SaleInfo sale=ModelQueryList.getModel(SaleInfo.class,saleOid,"*");
        PowerUtil.verifyStoreData(sale.getStore().getOid());
        List<GoodsOutVirtualStock> ls= ModelQueryList.getModelList(GoodsOutVirtualStock.class,
            new String[]{"*","record.*","record.record.stock.guest.oid"},null,
            QueryCondition.and(
                QueryCondition.eq("record.sale.oid",saleOid),
                QueryCondition.eq("record.record.stock.type", StockInfo.Type_Virtual)
            )
        );

        Map<String, List<GoodsOutVirtualStock>> guestMap=new HashMap<>();
        for(GoodsOutVirtualStock s : ls){
            String key=s.getRecord().getRecord().getStock().getGuest().getOid();
            guestMap.computeIfAbsent(key, k -> new ArrayList<>());
            guestMap.get(key).add(s);
        }
        List<String> goodsOids=new ArrayList<>();
        for(String guestOid : guestMap.keySet()){
            GuestInfo guest=new GuestInfo();
            guest.setOid(guestOid);
            TransactionManager tm=new TransactionManager();
            try {
                tm.begin();
                //生成调拨入库
                List<GoodsOutVirtualStock> recordList=guestMap.get(guestOid);
                StockInfo stock = new StockInfo();
                stock.setOrderNo(StoreNumberService.getNextStockNumber(sale.getStore().getOid()));
                stock.setStore(sale.getStore());
                stock.setStatus(OrderModel.Status_Register);
                stock.setType(StockInfo.Type_Allocate);
                stock.setInputDate(new Date());
                stock.setInputUser(sale.getInputUser());
                stock.setStockDate(sale.getSaleDate());
                stock.setGuest(guest);
                stock.setRemark(sale.getOrderNo()+"调货入库");
                List<GoodsStockRecord> stockRecords = new ArrayList<>();
                for(GoodsOutVirtualStock item : recordList){
                    GoodsStockRecord record = new GoodsStockRecord();
                    record.setRepository(item.getRepository());
                    record.setGoods(item.getRecord().getGoods());
                    record.setStockNum(item.getStockNum());
                    record.setPrice(item.getPrice());
                    record.setPreferential(item.getPreferential());
                    record.setRemark(item.getRemark());
                    stockRecords.add(record);
                    item.getRecord().setRecord(record);//填充新的库存属性，保存后就会有oid
                }
                getService(StockInfoService.class).saveAndSubmit(stock, stockRecords,false);
                getService(StockInfoService.class).check(stock.getOid(), stock.getStockDate(), stock.getRemark(), stock.getStore(), sale.getInputUser());
                //更新新的库存属性
                ModelUpdateUtil.updateModels(recordList.stream().map(GoodsOutVirtualStock::getRecord).toArray(GoodsOutRecord[]::new),"record.oid");
                goodsOids.addAll(stockRecords.stream().map(item->item.getGoods().getOid()).collect(Collectors.toList()));
                tm.commit();
            }catch (Exception e){
                tm.rollback();
                throw new MException(this.getClass(),"生成调拨入库失败:"+e.getMessage());
            }
        }
        StoreGoodsSupport.doneHandler(goodsOids.toArray(new String[0]));
    }

}
